﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using JM.JCY.Common.Utilities;
using JM.JCY.Common;
using Microsoft.SharePoint;
using JM.JCY.Proxy;

namespace JM.JCY.SharePointComponent.PersonalHome.PersonalInfo
{
    public partial class PersonalInfoUserControl : UserControl
    {
        public int _userId
        {
            set { ViewState["_userId"] = value; }
            get { return (int)ViewState["_userId"]; }
        }

        public string _userName
        {
            set { ViewState["_userName"] = value; }
            get { return (string)ViewState["_userName"]; }
        }

        public int _staffId
        {
            set { ViewState["_staffId"] = value; }
            get { return (int)ViewState["_staffId"]; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                _userName = ApplicationContext.Current.UserName.ToString();
                LoadUserInfo(_userName);
            }

        }

        private void LoadUserInfo(string userName)
        {
            using (UserManagementProxy proxy = new UserManagementProxy())
            {
                _staffId = proxy.GetUser(0,userName)[0].ID;

                var dt = proxy.GetUserForHome(_staffId);
                var userRow = dt[0];
                var dtCulture = proxy.GetUser(_staffId, string.Empty);

                this.lblNameDis.Text = userRow.UserName;
                this.lblDeptDis.Text = userRow.DeptName;
                this.imgUserPhotoDis.ImageUrl = userRow.PhotoImagePath;

                this.lblOffice.Text = userRow.OfficeAddress;
                this.lblOfficeNumber.Text = userRow.OfficeNumber;
                this.lblHomeNumber.Text = userRow.HomeNumber;
                this.lblMobileNumber.Text = userRow.MobileNumber;
                this.lblEmail.Text = userRow.Email;
                this.lblUserCulture.Text = dtCulture[0].Culture;

                this.txtOffice.Text = userRow.OfficeAddress;
                this.txtOfficeNumber.Text = userRow.OfficeNumber;
                this.txtHomeNumber.Text = userRow.HomeNumber;
                this.txtMobileNumber.Text = userRow.MobileNumber;
                this.txtEmail.Text = userRow.Email;
                this.ttaPersonalCul.InnerHtml = dtCulture[0].Culture;

                this.TRImage.Visible = false;
                this.TRButton.Visible = false;
            }
        }

        protected void imgBtnSubmitPhoto_Click(object sender, ImageClickEventArgs e)
        {
            if (this.filePhoto.HasFile)
            {
                string url = JCYSharePointHelper.UploadPicFile(this.filePhoto, Guid.NewGuid().ToString(), "/PersonalSite/UserPhoto");

                using (UserManagementProxy proxy = new UserManagementProxy())
                {
                    _staffId = proxy.GetUser(0, ApplicationContext.Current.UserName.ToString())[0].ID;
                    var dt = proxy.GetUser(_staffId, string.Empty);
                    dt[0].PhotoImagePath = url;
                    proxy.UpdateUserInfo(dt);
                }
            }

        }

        // 这里面是因为我无法调用sharepoint Helper里面的方法所以才放在这里面的
        public static string UploadPicFile(FileUpload fileupload, string fileName, string listName)
        {
            string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
            string url = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (fileupload.HasFile == true)
                        {
                            string filePath = fileupload.PostedFile.FileName;
                            if (filePath != "")
                            {
                                string fileExtension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower();
                                string fileTile = string.Format("{0}.{1}", fileName, fileExtension);
                                SPDocumentLibrary DocLib = GetPictureLibrary(listName);
                                SPListItem DocRow = DocLib.Items.Add(DocLib.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.File);
                                SPFolder folder = DocLib.RootFolder;
                                folder.ParentWeb.AllowUnsafeUpdates = true;
                                folder.Files.Add(DocLib.RootFolder.ServerRelativeUrl + "/" + fileTile, fileupload.FileBytes, true);
                                DocLib.Update();
                                folder.ParentWeb.AllowUnsafeUpdates = false;

                                SPFile File = SPContext.Current.Web.GetFile(folder.Url + "/" + fileName + "." + fileExtension);
                                url = GetAlternatePicUrl(File.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.ThumbNail);
                            }
                        }
                    }
                }
            });

            return url;
        }

        private static string GetAlternatePicUrl(string originalUrl, string type)
        {
            string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
            string url = originalUrl;
            string newUrl = "";

            string[] urlArr = originalUrl.Split('/');
            string fileName = urlArr[urlArr.Length - 1];
            fileName = fileName.Replace(".", "_");
            fileName += ".jpg";

            for (int i = 0; i < urlArr.Length - 1; i++)
            {
                if (i != 0)
                    newUrl += "/";
                newUrl += urlArr[i];
            }

            if (type == JCYConstant.SharePointHelper.PicType.ThumbNail)
                newUrl = newUrl + "/" + "_t";
            else if (type == JCYConstant.SharePointHelper.PicType.Optimized)
                newUrl = newUrl + "/" + "_w";

            return newUrl + "/" + fileName;
        }

        public static SPPictureLibrary GetPictureLibrary(string listName)
        {
            string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
            string listPath = String.Empty;
            listPath = listName;
            listPath = listPath.Replace(@"\", @"/");
            string[] paths = listPath.Split(new char[] { ',', ';', '|' });
            if (paths.Length >= 2)
            {
                using (SPWeb web = new SPSite(JCYUrl).OpenWeb(paths[0].TrimStart(new char[] { '/' })))
                {
                    return (SPPictureLibrary)web.GetList(paths[1]);
                }

            }
            else
            {
                using (SPWeb web = new SPSite(JCYUrl).OpenWeb())
                {
                    return (SPPictureLibrary)web.GetList(paths[0]);
                }
            }
        }

        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            using (UserManagementProxy proxy = new UserManagementProxy())
            {
                var dt = proxy.GetUser(_staffId, string.Empty);
                var editRow = dt[0];

                editRow.OfficeAddress = this.txtOffice.Text;
                editRow.OfficeNumber = this.txtOfficeNumber.Text;
                editRow.HomeNumber = this.txtHomeNumber.Text;
                editRow.MobileNumber = this.txtMobileNumber.Text;
                editRow.Email = this.txtEmail.Text;
                if (this.filePhoto.HasFile)
                {
                    editRow.PhotoImagePath = UploadPicFile(this.filePhoto, Guid.NewGuid().ToString(), "/PersonalSite/UserPhoto");
                }

                editRow.Culture = this.ttaPersonalCul.InnerText;
                JCYUtility.UpdateCommonFields(editRow, "admin");
                proxy.UpdateUserInfo(dt);

            }

            LoadUserInfo(SPContext.Current.Web.CurrentUser.Name);
            AfterSaveAction();
        }

        protected void lkbEditInfo_Click(object sender, EventArgs e)
        {
            this.txtOffice.Visible = true;
            this.txtOfficeNumber.Visible = true;
            this.txtHomeNumber.Visible = true;
            this.txtMobileNumber.Visible = true;
            this.txtEmail.Visible = true;
            this.ttaPersonalCul.Visible = true;
            this.TRImage.Visible = true;
            this.TRButton.Visible = true;

            this.lblOffice.Visible = false;
            this.lblOfficeNumber.Visible = false;
            this.lblHomeNumber.Visible = false;
            this.lblMobileNumber.Visible = false;
            this.lblEmail.Visible = false;
            this.lblUserCulture.Visible = false;
            this.TREditInfo.Visible = false;
        }

        private void AfterSaveAction()
        {
            this.txtOffice.Visible = false;
            this.txtOfficeNumber.Visible = false;
            this.txtHomeNumber.Visible = false;
            this.txtMobileNumber.Visible = false;
            this.txtEmail.Visible = false;
            this.ttaPersonalCul.Visible = false;
            this.TRImage.Visible = false;
            this.TRButton.Visible = false;

            this.lblOffice.Visible = true;
            this.lblOfficeNumber.Visible = true;
            this.lblHomeNumber.Visible = true;
            this.lblMobileNumber.Visible = true;
            this.lblEmail.Visible = true;
            this.lblUserCulture.Visible = true;
            this.TREditInfo.Visible = true;
        }

        protected void imgCancel_Click(object sender, ImageClickEventArgs e)
        {
            AfterSaveAction();
        }
    }
}
